package com.sca.bussiness.service.impl;

import com.sca.bussiness.config.RabbitConfig;
import com.sca.bussiness.entity.AbstractScheduleJob;
import com.sca.bussiness.service.ScheduleService;
import com.sca.bussiness.utils.GuidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author liuxianfei
 * @since 2020/11/20 11:59
 */
@Slf4j
@Service
public class ScheduleServiceImpl implements ScheduleService {

    private final RabbitTemplate rabbitTemplate;

    public ScheduleServiceImpl(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void addTimer(Long delaySeconds, AbstractScheduleJob job) {
        try {
            CorrelationData correlationData = new CorrelationData(GuidGenerator.generate());
            Map<String, Serializable> params = job.getParams();
            params.put("trigger", job.getClass().getCanonicalName());
            params.put("triggerAt", LocalDateTime.now().plusSeconds(delaySeconds));

            rabbitTemplate.convertAndSend(RabbitConfig.EXCHG_SCHEDULE, RabbitConfig.RTKEY_WAIT_POLL, params, correlationData);
            log.info("【schedule job added】[class:{}],[params:{}],[delaySeconds:{}]", job.getClass().getCanonicalName(), job.getParams(), delaySeconds);
        } catch (AmqpException amqpException) {
            log.error("定时任务添加失败", amqpException);
        }
    }

    @Override
    public void addTimer(LocalDateTime dateTime, AbstractScheduleJob job) {
        try {
            CorrelationData correlationData = new CorrelationData(GuidGenerator.generate());
            Map<String, Serializable> params = job.getParams();
            params.put("trigger", job.getClass().getCanonicalName());
            params.put("triggerAt", dateTime);

            rabbitTemplate.convertAndSend(RabbitConfig.EXCHG_SCHEDULE, RabbitConfig.RTKEY_WAIT_POLL, params, correlationData);
            log.info("【schedule job added】[class:{}],[params:{}],[dateTime:{}]", job.getClass().getCanonicalName(), job.getParams(), dateTime);
        } catch (AmqpException amqpException) {
            log.error("定时任务添加失败", amqpException);
        }
    }
}
